import React, { useState, useEffect } from 'react'
import { View, Text, Button } from '@tarojs/components'
import './index.scss'
import { AtTabBar, AtMessage } from 'taro-ui'
import Home from '../../components/index/index'
import Video from '../../components/video/index'
import Tag from '../../components/tag/index'
import About from '../../components/about/index'
import Taro from '@tarojs/taro'
import LoginModal from '../../components/login/index'
import { getNewToken } from '../../api/index'

export default () => {
  const [current, setCurrent] = useState(0)
  const [openLogin, setOpenLogin] = useState(false)
  const [trigger, setTrigger] = useState(Symbol())

  const setComponents = () => {
    if (current === 0) return <Home />
    if (current === 1) return <Video />
    if (current === 2) return <Tag />
    else if (current === 3) return <About></About>
  }

  const changeTable = (val) => {
    if (val === 0) {
      setCurrent(val)
    } else {
      if (Taro.getStorageSync('token')) {
        setCurrent(val)
      } else {
        setOpenLogin(true)
        setTrigger(Symbol())
      }
    }
  }

  useEffect(() => {
    Taro.getStorage({
      key: 'id',
      success: async function (res) {
        await getNewToken({
          id: res.data
        })
      }
    })
  }, [])

  return (
    <View>
      <AtMessage></AtMessage>
      {/* <Button onClick={tapToChart}>click me</Button> */}
      {setComponents()}
      {Taro.getStorageSync('token') ? (
        ''
      ) : (
        <LoginModal open={openLogin} trigger={trigger}></LoginModal>
      )}
      <AtTabBar
        className="at-tab-bar"
        selectedColor="rgb(250, 138, 173)"
        color="grey"
        fixed
        tabList={[
          { title: 'UP主', iconType: 'home' },
          { title: '视频', iconType: 'video' },
          { title: '标签', iconType: 'tag' },
          { title: '个人中心', iconType: 'user' }
        ]}
        onClick={(val) => changeTable(val)}
        current={current}
      />
    </View>
  )
}
